package com.ed.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ed.constant.UserConstant;
import com.ed.context.UserContext;
import com.ed.domain.*;
import com.ed.dto.EditUserDTO;
import com.ed.dto.UserPageByConditionDTO;
import com.ed.dto.UserRegisterDTO;
import com.ed.exception.BaseException;
import com.ed.mapper.*;
import com.ed.result.PageResult;
import com.ed.service.UserService;
import com.ed.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * @author 32727
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2025-06-19 10:35:38
 */
@Service
public class UserServiceImpl extends ServiceImpl<IUserMapper, User> implements UserService {
	
	@Autowired
	private IUserMapper userMapper;
	@Autowired
	private IChatConversationMapper chatConversationMapper;
	@Autowired
	private IChatMessageMapper chatMessageMapper;
	@Autowired
	private IResponseMapper responseMapper;
	@Autowired
	private IResponseDetailsMapper responseDetailsMapper;
	
	/**
	 * 注册
	 *
	 * @param userRegisterDTO
	 */
	@Override
	public void register(UserRegisterDTO userRegisterDTO) {
		String name = userRegisterDTO.getName();
		String phone = userRegisterDTO.getPhone();
		String password = userRegisterDTO.getPassword();
		String checkPassword = userRegisterDTO.getCheckPassword();
		//1. 参数校验
		//判空
		if (StrUtil.isBlank(name)
			|| StrUtil.isBlank(phone)
			|| StrUtil.isBlank(password)
			|| StrUtil.isBlank(checkPassword)) {
			throw new BaseException("参数为空");
		}
		//长度校验
		if (name.length() < 1) {
			throw new BaseException("姓名过短");
		} else if (name.length() > 30) {
			throw new BaseException("姓名过长");
		}
		if (!Integer.valueOf(11).equals(phone.length())) {
			throw new BaseException("请输入正确手机号");
		}
		if (password.length() < 8) {
			throw new BaseException("密码过短");
		} else if (password.length() > 20) {
			throw new BaseException("密码过长");
		}
		//密码相同
		if (!password.equals(checkPassword)) {
			throw new BaseException("两次密码不一致");
		}
		//一个手机只能注册一个账号
		Long count = lambdaQuery().eq(User::getPhone, phone).count();
		if (count > 0) {
			throw new BaseException("手机号已注册");
		}
		//2. 保存到数据库
		User user = new User();
		//时间戳生成随机昵称
		user.setUsername(UserConstant.USER_NICKNAME_PREFIX + System.currentTimeMillis());
		user.setPhone(phone);
		user.setName(name);
		user.setPassword(password);
		//普通用户权限
		user.setPermission(2);
		//uuid 生成住院号
		user.setHospitalNum(UserConstant.USER_HOSPITALNUM_PREFIX + UUID.randomUUID());
		user.setUpdateTime(LocalDateTime.now());
		boolean result = save(user);
		if (!result) {
			throw new BaseException("系统错误，请重新注册");
		}
	}
	
	/**
	 * 登录
	 *
	 * @param user
	 * @return
	 */
	@Override
	public String login(User user) {
		String phone = user.getPhone();
		String password = user.getPassword();
		//1. 参数校验
		//判空
		if (StrUtil.isBlank(phone)
			|| StrUtil.isBlank(password)) {
			throw new BaseException("参数为空");
		}
		//长度校验
		if (!Integer.valueOf(11).equals(phone.length())) {
			throw new BaseException("请输入正确手机号");
		}
		if (password.length() < 8) {
			throw new BaseException("密码过短");
		} else if (password.length() > 20) {
			throw new BaseException("密码过长");
		}
		//2. 登录校验
		User loginUser = lambdaQuery()
			.eq(User::getPhone, phone)
			.select(User::getId, User::getUsername, User::getPassword)
			.one();
		if (loginUser == null) {
			throw new BaseException("请先注册");
		}
		if (!password.equals(loginUser.getPassword())) {
			throw new BaseException("密码错误");
		}
		//3. 获取 jwt token
		Integer userId = loginUser.getId();
		String username = loginUser.getUsername();
		if (userId == null || userId <= 0 || StrUtil.isBlank(username)) {
			throw new BaseException("参数异常");
		}
		String token = JwtUtil.createJwt(userId, username);
		return token;
	}
	
	@Override
	public String loginAdmin(User user) {
		String phone = user.getPhone();
		String password = user.getPassword();
		//1. 参数校验
		//判空
		if (StrUtil.isBlank(phone)
			|| StrUtil.isBlank(password)) {
			throw new BaseException("参数为空");
		}
		//长度校验
		if (!Integer.valueOf(11).equals(phone.length())) {
			throw new BaseException("请输入正确手机号");
		}
		if (password.length() < 8) {
			throw new BaseException("密码过短");
		} else if (password.length() > 20) {
			throw new BaseException("密码过长");
		}
		//2. 登录校验
		User loginUser = lambdaQuery()
			.eq(User::getPhone, phone)
			.select(User::getId, User::getUsername, User::getPassword, User::getPermission)
			.one();
		if (loginUser == null) {
			throw new BaseException("请先注册");
		}
		if (!password.equals(loginUser.getPassword())) {
			throw new BaseException("密码错误");
		}
		if (loginUser.getPermission() != 1) {
			throw new BaseException("未获取管理员权限");
		}
		//3. 获取 jwt token
		Integer userId = loginUser.getId();
		String username = loginUser.getUsername();
		if (userId == null || userId <= 0 || StrUtil.isBlank(username)) {
			throw new BaseException("参数异常");
		}
		String token = JwtUtil.createJwt(userId, username);
		return token;
	}
	
	@Override
	public String loginMessage(User user) {
		String phone = user.getPhone();
		//1. 参数校验
		//判空
		//长度校验
		if (!Integer.valueOf(11).equals(phone.length())) {
			throw new BaseException("请输入正确手机号");
		}
		//2. 登录校验
		User loginUser = lambdaQuery()
			.eq(User::getPhone, phone)
			.select(User::getId, User::getUsername, User::getPassword)
			.one();
		if (loginUser == null) {
			throw new BaseException("请先注册");
		}
		//3. 获取 jwt token
		Integer userId = loginUser.getId();
		String username = loginUser.getUsername();
		if (userId == null || userId <= 0 || StrUtil.isBlank(username)) {
			throw new BaseException("参数异常");
		}
		String token = JwtUtil.createJwt(userId, username);
		return token;
	}
	
	/**
	 * 编辑用户信息
	 *
	 * @param userDto
	 */
	@Override
	public void updateUserInfo(EditUserDTO userDto) {
		//1.将userDto转为user对象
		User user = BeanUtil.copyProperties(userDto, User.class);
		user.setId(UserContext.getCurrentUser());
		//2.修改用户信息
		userMapper.updateById(user);
	}
	
	/**
	 * 管理员分页查询用户信息
	 *
	 * @param userPageByConditionDTO
	 * @return
	 */
	@Override
	public PageResult pageByCondition(UserPageByConditionDTO userPageByConditionDTO) {
		Integer pageNo = userPageByConditionDTO.getPageNo();
		Integer pageSize = userPageByConditionDTO.getPageSize();
		//姓名
		String name = userPageByConditionDTO.getName();
		if (pageNo == null || pageNo < 0) {
			pageNo = 0;
		}
		if (pageSize == null || pageSize <= 0) {
			pageSize = 10;
		}
		LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
		//id、真实姓名、手机号、住院号
		wrapper.select(User::getId, User::getName, User::getPhone, User::getHospitalNum);
		if (!StrUtil.isBlank(name)) {
			wrapper.like(User::getName, name);
		}
		IPage<User> page = page(new Page<>(pageNo, pageSize), wrapper);
		if (page == null) {
			throw new BaseException("查询失败");
		}
		PageResult pageResult = new PageResult();
		pageResult.setTotal(page.getTotal());
		pageResult.setRecords(page.getRecords());
		return pageResult;
	}
	
	/**
	 * 管理员删除用户
	 *
	 * @param id
	 */
	@Override
	@Transactional
	public void deleteUser(Integer id) {
		User user = getById(id);
		if (user == null) {
			throw new BaseException("该用户不存在！");
		}
		//删除所有关联信息
		//1.删除ai会话记录
		QueryWrapper<ChatMessage> chatMessageQueryWrapper = new QueryWrapper<>();
		QueryWrapper<ChatConversation> conversationQueryWrapper = new QueryWrapper<>();
		conversationQueryWrapper.eq("user_id",id);
		List<ChatConversation> chatConversations = chatConversationMapper.selectList(conversationQueryWrapper);
		//1.1找出该用户所有会话id
		List<String> conIds = chatConversations.stream().map(ChatConversation::getConversationId).toList();
		//1.2根据会话id找出所有信息记录,删除
		if (!conIds.isEmpty()){
			QueryWrapper<ChatMessage> delMessageQuery = chatMessageQueryWrapper.in("conversation_id", conIds);
			int deleteMessages = chatMessageMapper.delete(delMessageQuery);
		}
		//1.3删除该用户的所有会话
		int deleteCons = chatConversationMapper.delete(conversationQueryWrapper);
		//2.删除答题记录
		//2.1 找出所有response
		QueryWrapper<Response> responseQueryWrapper = new QueryWrapper<>();
		responseQueryWrapper.eq("user_id",id);
		List<Response> responses = responseMapper.selectList(responseQueryWrapper);
		List<Integer> resIds = responses.stream().map(Response::getId).toList();
		//2.2找出所有details
		if (!resIds.isEmpty()){
			QueryWrapper<ResponseDetails> responseDetailsQueryWrapper = new QueryWrapper<>();
			responseDetailsQueryWrapper.in("response_id",resIds);
			//先删除details
			int detailsRows = responseDetailsMapper.delete(responseDetailsQueryWrapper);
		}
		//最后删除response
		int responseRows = responseMapper.delete(responseQueryWrapper);

		boolean result = removeById(id);
		if (!result) {
			throw new BaseException("删除用户失败！");
		}
	}
}





